﻿/*-------------------------------------------------------------------------
* 命名空间: SiliconSelect.ViewModels/UserManagementViewModel
* 类       名: UserManagementViewModel
* 功      能:  TD
* 时      间:  2023/8/7 17:26:02
* 版      本:  V1.0
* 作      者:  Fioman
* 格      言:  Talk is cheap,show me the code ^_^
*-------------------------------------------------------------------------*/
using SiliconSelect.Base;
using SiliconSelect.BLL;
using SiliconSelect.Common;
using SiliconSelect.DAL.DataEntity;
using SiliconSelect.Models;
using SiliconSelect.Views.UserOperatorDialog;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Threading;

namespace SiliconSelect.ViewModels
{

    public class UserManagementViewModel : NotifyBase
    {
        public UserManagementViewModel()
        {
            UserInfoList = new ObservableCollection<UserModel>();
            ReloadUserData(); // 从数据库中从新加载用户表数据
            UserEditor = new UserModel();
            UserOperateCommand = new Command(DoUserOperateCommand);
        }

        /// <summary>
        /// 添加用户的命令,添加用户的时候要显示另外一个窗口.
        /// </summary>
        public Command UserOperateCommand { get; set; }
        private void DoUserOperateCommand(object obj)
        {
            if ((obj as string)!.ToLower() == "add")
            {
                UserAddWindow userEditorWindow = new UserAddWindow(ReloadUserData);
                UserEditor!.Username = "";
                UserEditor.Password = "";
                UserEditor.Role = "操作员";
                userEditorWindow.DataContext = UserEditor;
                userEditorWindow.ShowDialog();
            }
            else if ((obj as string)!.ToLower() == "editor")
            {
                // 编辑用户,首先是要拿到编辑用户的数据,怎么拿到呢? 根据
                if (SelectedIndex == -1)
                {
                    MessageBox.Show("请选中你要编辑所在行!");
                }
                else
                {
                    UserEditorWindow userEditorWindow = new UserEditorWindow(ReloadUserData, UserInfoList![SelectedIndex].Username!);
                    UserEditor!.Username = UserInfoList![SelectedIndex].Username;
                    UserEditor!.Password = UserInfoList![SelectedIndex].Password;
                    UserEditor!.Role = UserInfoList![SelectedIndex].Role;
                    UserEditor!.CreateBy = UserInfoList![SelectedIndex].CreateBy;
                    UserEditor!.CreateTime = UserInfoList![SelectedIndex].CreateTime;
                    UserEditor!.LastLoginTime = UserInfoList![SelectedIndex].LastLoginTime;
                    userEditorWindow.DataContext = UserEditor;
                    userEditorWindow.ShowDialog();
                }

            }
            else
            {
                // 删除
                if (SelectedIndex == -1)
                {
                    MessageBox.Show("请选中你要删除的行!");
                }
                else
                {
                    string deleteUsername = UserInfoList![SelectedIndex].Username!;
                    DataResult result = LocalDataAccess.DeleteUserDbByUsername("Username", deleteUsername);
                    if (result.State)
                    {
                        MessageBox.Show("删除成功!");
                        ReloadUserData();
                    }
                    else
                    {
                        MessageBox.Show($"删除失败: {result.Message}");
                    }
                }
            }
        }


        private UserModel? _userEditor;

        public UserModel? UserEditor
        {
            get { return _userEditor; }
            set { SetProperty(ref _userEditor, value); }
        }


        /// <summary>
        /// 所有的用户
        /// </summary>
        private ObservableCollection<UserModel>? _userInfoList;

        public ObservableCollection<UserModel>? UserInfoList
        {
            get
            {
                return _userInfoList;
            }
            set { SetProperty(ref _userInfoList, value); }
        }

        /// <summary>
        /// 选中的用户索引.根据这个去获取,默认是一行也不选择
        /// </summary>
        private int _selectedIndex = -1;

        public int SelectedIndex
        {
            get { return _selectedIndex; }
            set { SetProperty(ref _selectedIndex, value); }
        }


        /// <summary>
        /// 从数据库中加载所有的用户信息
        /// </summary>
        private void ReloadUserData()
        {
            Task.Run(() =>
            {
                try
                {
                    DataResult<List<UserEntity>> dataResult = LocalDataAccess.GetUserList();
                    if (!dataResult.State)
                    {
                        LogHelper.WriteLog(LogType.Exception, dataResult.Message);
                        MessageBox.Show($"数据加载异常: {dataResult.Message}");
                    }
                    Application.Current?.Dispatcher.Invoke(() =>
                    {
                        UserInfoList!.Clear();
                        if (dataResult.Data != null)
                        {
                            foreach (UserEntity user in dataResult.Data!)
                            {
                                UserModel temp = new UserModel()
                                {
                                    Username = user.Username,
                                    Password = user.Password,
                                    Role = user.Role,
                                    CreateBy = user.CreateBy,
                                    CreateTime = user.CreateTime,
                                    LastLoginTime = user.LastLoginTime,
                                };
                                UserInfoList.Add(temp);
                            }
                        }
                    });

                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog(LogType.Exception, ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!));
                }
            });
        }
    }
}
